package com.yunhoo.pay.util;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.LoginParam;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author admin
 */
public class BillNumBuilder {

    /**
     * 
     * @param client
     * @return 单据编号
     * @throws SQLException 
     */
    public static String buildNum(SqlMapClient client) throws SQLException {
        String month = curMonth();
        Map map = new HashMap();
        map.put("orgCode", LoginParam.getOrg().getCode());
        map.put("iyear", LoginParam.getIyear());
        map.put("imonth", month);
        Integer maxCode = (Integer) client.queryForObject("voucher.maxNum", map);

        if (maxCode == null) throw new SQLException();

        return String.format(month + "%04d%n", maxCode + 1).trim();
    }

    private static String curMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Integer month = calendar.get(Calendar.MONTH) + 1;
        return String.format("%02d%n", month).trim();
    }

    public static void main(String[] args) {
        System.out.println("month : " + curMonth());
        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();
            String num = buildNum(client);
            System.out.println("num :  " + num);
            client.commitTransaction();
        } catch (SQLException ex) {
            System.out.println("异常");
            Logger.getLogger(BillNumBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                client.endTransaction();
            } catch (SQLException ex) {
                Logger.getLogger(BillNumBuilder.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
